#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author： 青城子
# datetime： 2022/2/26 16:10 
# ide： PyCharm

import time
import os
import uiautomator2 as u2

from conf import settings
from utils.loghandler import logger


class PublicOperation:
    """
    操作安卓app&设备父类
    """

    def __init__(self):
        self.devices_no = settings.DEVICES_NUMBER
        self.driver_ip = settings.DEVICES_IP
        self.page_name = settings.APP_PACKAGE
        self.apk_path = settings.APK_PATH
        self.img_time = time.strftime("%Y-%m-%d %H_%M_%S")  # 生成截图片已当前时间命名图片名称
        self.directory_time = time.strftime("%Y-%m-%d")  # 当日截图目录名称
        self.root_directory = settings.BASE_DIR  # 项目根目录
        self.screen_dir = settings.DIR_PATH_DICT.get("screenshots")
        if settings.DEFAULT:
            self.devices = u2.connect_usb(self.devices_no)
        else:
            self.devices = u2.connect_adb_wifi(self.driver_ip)
        self.size = self.get_size()  # 移动设备屏幕尺寸

    def create_screens_hot_dir(self, *args):
        # 创建截图一级目录
        try:
            if os.path.exists(self.screen_dir):  # 截图的目录screenshots是否存在
                pass
            else:
                os.mkdir("{0}".format(self.screen_dir))
        except Exception as error:
            logger().info("创建截图目录失败:{0}".format(error))

        # 创建二级目录
        try:
            if os.path.exists(r"{0}\{1}".format(self.screen_dir, self.directory_time)):
                """
                 判断screenshots目录下是否存在(2020-04-15)格式命名的目录
                """
                pass
            else:
                os.mkdir(r"{0}\{1}".format(self.screen_dir, self.directory_time))
        except Exception as error:
            logger().info("创建每日截图目录失败:{0}".format(error))

        # 创建三级目录用于存放用例执行成功时截图
        try:
            if os.path.exists(r"{0}\{1}\{2}".format(self.screen_dir, self.directory_time, "success")):
                pass
            else:
                os.mkdir(r"{0}\{1}\{2}".format(self.screen_dir, self.directory_time, "success"))
        except Exception as error:
            logger().info("创建每日成功截图目录失败:{0}".format(error))
        direct_success = r"{0}\{1}\{2}".format(self.screen_dir, self.directory_time, "success")

        # 创建三级目录，用于保存用例执行失败时截图信息
        if args[0]:
            try:
                if os.path.exists(r"{0}\{1}\{2}".format(self.screen_dir, self.directory_time, "errors")):
                    pass
                else:
                    os.mkdir(r"{0}\{1}\{2}".format(self.screen_dir, self.directory_time, "error"))

            except Exception as error:
                logger().info("每日错误目录失败:{0}".format(error))

        direct_error = r"{0}\{1}\{2}".format(self.screen_dir, self.directory_time, "error")
        return direct_success, direct_error,

    def screenshots(self, type_str=None,error=None):
        """
        截图
        :return:
        """
        dir_success, dir_error = self.create_screens_hot_dir(error)
        # 用例执行成功时页面截图
        if type_str:
            image_page = r"{0}\{1}{2}.png".format(dir_success, type_str, self.img_time)
        else:
            image_page = r"{0}\{1}.png".format(dir_success, self.img_time)

        if error:
            # 代码执行错误时，进行截图
            image_page_error = r"{0}\{1}.png".format(dir_error, self.img_time)
            self.devices.screenshot(image_page_error)
        else:
            self.devices.screenshot(image_page)

    def app_info(self):
        """
        查看app详细信息
        :return:
        """
        return self.devices.app_info(package_name=self.page_name)

    def current_app(self):
        """
        查看当前运行的app信息
        :return:
        """
        return self.devices.app_current()

    def get_all_install_app(self):
        """
        获取移动设备中安装的所有app信息
        :return:
        """
        return self.devices.app_list()

    def get_all_current_run_app(self):
        """
        获取移动设备中所有正在运行的app信息
        :return:
        """
        time.sleep(2)
        return self.devices.app_list_running()

    def start_app(self):
        """
        启动app ,page_name app包名
        :return:
        """
        self.devices.app_start(package_name=self.page_name)

    def stop_app(self):
        """
        关闭当前运行app
        :return:
        """
        self.devices.app_stop(package_name=self.page_name)

    def clear_app_cache(self):
        """
        清除app缓存
        :return:
        """
        self.devices.app_clear(self.page_name)

    def uninstall_app(self):
        """
        卸载app
        :return: 删除成功后返回True
        """
        return self.devices.app_uninstall(package_name=self.page_name)

    def app_uninstall_all(self):
        """
        卸载当前安卓手机上所有第三方app，u2项目不会卸载
        :return:
        """
        self.devices.app_uninstall_all()

    def app_install(self):
        """
        安装app，参数为apk路径
        :return:
        """
        self.devices.app_install(self.apk_path)

    def devices_detailed_info(self):
        """
        查看当前连接设备详细详细
        :return:
        """
        return self.devices.device_info

    def info_devices(self):
        """
        查看连接设备的信息
        :return:
        """
        return self.devices.info

    def check_u2_run(self):
        """
        查看u2服务是否启动
        :return: True或False
        """
        time.sleep(5)
        return self.devices.uiautomator.running()

    def start_u2(self):
        """
        启动u2服务
        :return:
        """
        time.sleep(2)
        self.devices.uiautomator.start()

    def stop_u2(self):
        """
        停止u2服务
        :return:
        """
        self.devices.uiautomator.stop()

    def get_size(self):
        """
        查看设备分辨率
        :return: 元祖类型分辨率
        """
        return self.devices.window_size()

    def info_devices_ip(self):
        """
        查看设备IP地址
        :return:
        """
        return self.devices.wlan_ip

    def location_app_text(self, value):
        """
        全文本匹配
        :return:
        """
        return self.devices(text=value)

    def location_app_text_contains(self, value):
        """
        文本匹配，包含即可匹配到
        :return:
        """
        return self.devices(textContains=value)

    def location_app_text_starts_with(self, value):
        """
        起始文本
        :param value:
        :return:
        """
        return self.devices(textStartsWith=value)

    def location_app_class_name(self, *args):
        """
        className来获取定位,注意索引下标
        :param args:
        :return:
        """
        return self.devices(className=args[0], instance=args[1])

    def location_resource_id(self, value):
        """
        资源ID
        :param value:
        :return:
        """
        return self.devices(resourceId=value)

    def location_xpath(self, xpath):
        """
        xpath定位
        :param xpath:
        :return:
        """
        return self.devices.xpath(xpath)

    def screen_off(self):
        """
        息屏
        :return:
        """
        self.devices.screen_off()

    def screen_on(self):
        """
        点亮屏幕
        :return:
        """
        self.devices.screen_on()

    def unlock(self):
        """
        解锁直接打开输入密码界面
        :return:
        """
        self.devices.unlock()

    def return_home(self, value="home"):
        """
        返回到页面,默认是home页面，传入back返回上一级页面
        :return:
        """
        self.devices.press(value)

    def swipe_left_right(self, values="left"):
        """
        滑动屏幕，默认左滑屏
        :return:
        """
        self.swipe_left_right(values)

    def handle_watcher(self, xpath):
        """
        监控器,只能是xpath定位
        :return:
        """
        self.devices.watcher.when(xpath)

    def start_watcher(self):
        """
        启动监控器
        :return:
        """
        self.devices.watcher.start()

    def stop_watcher(self):
        """
        停止监控器
        :return:
        """
        self.devices.watcher.stop()

    def swipe_points(self, value=[]):
        """
        滑动屏幕，根据values传入的坐标定位元素,不要太快延时0.2秒
        :param value:
        :return:
        """
        self.devices.swipe_points(points=value, duration=0.2)

    def up_swipe_size(self):
        """
        获取屏幕向上滑动
        :return:
        """
        x1 = int(self.size[0] * 0.5)  # x轴中间
        y1 = int(self.size[1] * 0.85)  # y轴最下面
        y2 = int(self.size[1] * 0.15)  # y轴最上面
        self.devices.swipe(x1, y1, x1, y2)

    def down_swipe_size(self):
        """
        屏幕向下滑动
        :return:
        """
        x1 = int(self.size[0] * 0.5)  # x轴中间
        y1 = int(self.size[1] * 0.9)  # y轴最下面
        y2 = int(self.size[1] * 0.15)  # y轴最上面
        self.devices.swipe(x1, y2, x1, y1)

    def wait_activity(self, activity):
        """
        等待activity,timeout=10秒
        :return:
        """
        print("到啦啊啊啊",activity)
        self.devices.wait_activity(activity, timeout=10)

    def get_message(self):
        """
        获取toast文本信息
        :return:
        """
        return self.devices.toast.get_message()
